﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Collections;
using System.IO;

namespace RemoteDll
{
    public class RemoteLoader : MarshalByRefObject, IDisposable
    {
        public RemoteLoader(string dllName)
        {
            if (assembly == null)
            {
                assembly = Assembly.LoadFrom(dllName);
            }
        }

        ~RemoteLoader()
        {
            dispose(true);
        }

        public Assembly assembly = null;

        public Assembly LoadAssembly(string dllName)
        {
           // try
            //{
                assembly = Assembly.LoadFrom(dllName);
                return assembly;
            //}
            //catch (Exception)
            //{
            //    throw new AssemblyLoadFailureException();
            //}
        }

        public string GetAssemblyVersion(string dllName)
        {
            assembly = Assembly.LoadFrom(dllName);
            AssemblyName name = assembly.GetName();
            return name.Version.ToString();
        }
        public object Invoke(string fullClassName, string methodName, params Object[] args)
        {
            if (assembly == null)
                return false;
            Type tp = assembly.GetType(fullClassName);
            if (tp == null)
                return false;
            MethodInfo method = tp.GetMethod(methodName);
            if (method == null)
                return false;
            Object obj = Activator.CreateInstance(tp);
            method.Invoke(obj, args);
            return obj;
        }
        public ArrayList LoadAssemblies(ArrayList dllFileList)
        {
            ArrayList assemblyList = new ArrayList();
            foreach (string dllFile in dllFileList)
            {
                FileInfo info = new FileInfo(dllFile);
                if (info.Extension == ".dll")
                {
                    Assembly a = LoadAssembly(dllFile);
                    assemblyList.Add(a);
                }
            }

            return assemblyList;
        }

        #region IDisposable 成员

        public void Dispose()
        {
            dispose(true);
        }

        private void dispose(bool disposing)
        {
            if (disposing)
            {
                assembly = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect(0);
            }
        }

        #endregion
    }
}

